import React, {PureComponent} from "react";
import {connect} from "react-redux";
import {Modal, notification} from "antd";
import FormEditor from '../../components/FormEditor';
import {hideEdit, modify, query, updateModel} from "./actions";
import {formatDate, formatStrToDate} from "../../lib/func";
import {getCurrentOrganization, getPrincipal} from "../../lib/identity";

class ModifyModal extends PureComponent {
    handleModify = () => {
        const formEditor = this.formEditor.props.form;
        if (formEditor) {
            const {dispatch, model, filter} = this.props;
            formEditor.validateFieldsAndScroll((err, values) => {
                if (!err) {
                    const updateModel = {...model, ...values};
                    const principal = getPrincipal();
                    updateModel.pickDate = formatDate(values.pickDate);
                    updateModel.preReturnDate = formatDate(values.preReturnDate);
                    updateModel.actReturnDate = formatDate(values.actReturnDate);
                    if (values.pickDate !== undefined && values.actReturnDate !== undefined) {
                        // 算出时效
                        const date1 = formatStrToDate(values.actReturnDate);
                        const date2 = formatStrToDate(values.pickDate);
                        updateModel.useDays = Math.abs(date2.diff(date1, 'day'));
                    }
                    dispatch(modify({...updateModel, "opId": principal.id})).then(action => {
                        if (action.error !== true) {
                            dispatch(hideEdit());
                            dispatch(query({
                                ...filter,
                                "organizationId": getCurrentOrganization(),
                                "userId": getPrincipal().id
                            }));
                            notification.success({
                                message: '修改成功'
                            });
                        } else {
                            notification.error({
                                message: '修改失败:' + action.message
                            });
                        }
                    });
                }
            })
        }
    };
    handleCancel = () => {
        const {dispatch} = this.props;
        dispatch(hideEdit());
    };

    handleChangePickDate = date => {
        const {model, dispatch} = this.props;
        const dateStr = formatDate(date);
        if (date && model.lessReturnDays) {
            model.preReturnDate = date.add(model.lessReturnDays, 'days');
        }
        model.pickDate = formatStrToDate(dateStr);
        dispatch(updateModel(model));
    };
    handleChangeReturnDays = day => {
        const {model, dispatch} = this.props;
        const dateStr = formatDate(model.pickDate);
        const date = formatStrToDate(model.pickDate);
        model.lessReturnDays = day;
        if (day && date) {
            model.preReturnDate = date.add(day, 'days');
            model.pickDate = formatStrToDate(dateStr);
        }
        dispatch(updateModel(model));
    };

    render() {
        const {loading, clientList, visible, model, organizations, orderFollowStatusList, cabinetTypeList} = this.props;
        const schema = [
            {
                title: '订单信息',
                fields: [
                    {
                        field: 'clientId',
                        title: '客户',
                        type: 'listSelector',
                        readonly: model.lock,
                        controlProps: {
                            dataSource: clientList,
                            labelField: "name",
                            valueField: "id"
                        },
                        fieldOptions: {
                            rules: [{required: true, message: '请选择客户'}]
                        }
                    }, {
                        field: 'cabinetNumber',
                        title: '柜号',
                        readonly: true,
                        fieldOptions: {
                            rules: [{required: true, message: '请输入柜号'}],
                        }
                    }, {
                        field: 'cabinetType',
                        title: '柜型',
                        readonly: model.lock,
                        fieldOptions: {
                            rules: [{required: true, message: '请输入柜型'}],
                        },
                        type: 'autoComplete',
                        controlProps: {
                            dataSource: cabinetTypeList
                        }
                    }, {
                        field: 'pickDate',
                        title: '提箱日期',
                        type: 'date',
                        readonly: true,
                        controlProps: {
                            onChange: this.handleChangePickDate
                        },
                        fieldOptions: {
                            rules: [{required: true, message: '请选择提箱日期'}],
                        }
                    }, {
                        field: 'pickNumber',
                        title: '提箱码',
                        readonly: model.lock,
                        type: 'text'
                    }, {
                        field: 'lessReturnDays',
                        title: '还箱剩余天数',
                        type: 'number',
                        readonly: model.lock,
                        placeholder: "单位(天)",
                        controlProps: {
                            onChange: this.handleChangeReturnDays
                        },
                        fieldOptions: {
                            rules: [{required: true, message: '请输入还箱剩余天数'}],
                        }
                    }, {
                        field: 'preReturnDate',
                        title: '预计还箱日期',
                        type: 'date',
                        readonly: true
                    }, {
                        field: 'actReturnDate',
                        title: '实际还箱日期',
                        readonly: model.lock,
                        type: 'date'
                    }, {
                        field: 'returnPlace',
                        title: '还箱地',
                        readonly: model.lock,
                        type: 'text'
                    }, {
                        field: 'returnCommand',
                        title: '还箱令',
                        readonly: model.lock,
                        type: 'text'
                    }
                    /*, {
                        field: 'carFile',
                        title: '随车文件',
                        readonly: model.lock,
                        type: 'autoComplete',
                        controlProps: {
                            dataSource: orderFollowStatusList
                        }
                    }*/
                    /*, {
                        field: 'orderNumber',
                        title: '运单',
                        readonly: model.lock,
                        type: 'autoComplete',
                        controlProps: {
                            dataSource: orderFollowStatusList
                        }
                    }*/
                    , {
                        field: 'remark',
                        readonly: model.lock,
                        title: '备注',
                        type: 'textArea'
                    }
                ]
            }];
        if (getPrincipal().admin) {
            schema[0].fields.splice(0, 0, {
                field: 'organizationId',
                title: '所属机构',
                type: 'treeSelector',
                readonly: model.lock,
                controlProps: {
                    treeData: organizations,
                    labelField: "name",
                    valueField: "id",
                    treeCheckable: false
                },
                fieldOptions: {
                    rules: [{required: true, message: '请选择所属机构'}]
                }
            });
        }
        return (
            <Modal
                title="修改"
                visible={visible}
                onOk={this.handleModify}
                onCancel={this.handleCancel}
                confirmLoading={loading}
                okText="保存"
                cancelText="取消"
                width="90%"
            >
                <FormEditor
                    schema={schema}
                    column={3}
                    defaultReadonly={false}
                    showActionBar={false}
                    defaultValues={model}
                    wrappedComponentRef={inst => (this.formEditor = inst)}
                />
            </Modal>
        );
    }
}

const mapStateToProps = state => {
    return {
        ...state.containerOrder.modify,
        clientList: state.home.clients,
        carrierList: state.home.carriers,
        orderFollowStatusList: state.common.orderFollowStatusList,
        packageReturnType: state.common.packageReturnType,
        cabinetTypeList: state.common.cabinetTypeList,
        organizations: state.home.organizations,
        filter: state.containerOrder.list.filter
    };
};


export default connect(mapStateToProps)(ModifyModal);
